import Taro from '@tarojs/taro';
import config from './config';

const uploadImage = ({ list = [], maxNum = 9, maxSize = 10 * 1240 * 1024, callback }) => {
  Taro.chooseImage({
    count: maxNum - list.length,
    success: res => {
      Taro.showLoading({
        title: '上传中...',
      });
      // 本地缓存展示
      let newList = [...list];
      // 开始上传
      let num = res.tempFiles.length;
      res.tempFiles.map(tempFile => {
        if (tempFile.size > maxSize) {
          Taro.showToast({
            title: '只能上传小于10M的图片',
            icon: 'none',
          });
          num--;
          return null;
        }
        // 保存当前图片的顺序
        newList.push(tempFile);
        upload(tempFile.path, data => {
          num--;
          if (num === 0) {
            Taro.hideLoading();
          }
          // 过滤上传失败的图片
          if (!data) {
            newList.filter(item => {
              return !(item.path && item.path === tempFile.path);
            });
          } else {
            // 上传成功保存当前url
            newList = newList.map(item => {
              if (tempFile.path === item.path) {
                return {
                  ...item,
                  fileId: data.models[0].id,
                  fileCode: data.models[0].code,
                };
              }
              return item;
            });
          }
          callback(newList);
        });
      });
    },
  });
};

const upload = (path, callback) => {
  Taro.uploadFile({
    url: `${config.filePrefix}/file/file/upload`,
    filePath: path,
    name: 'file',
    header: {
      'Content-Type': 'application/x-www-form-urlencoded;text/html; charset=utf-8',
      Authorization: Taro.getStorageSync('token'),
      Client: '04',
    },
    success(res) {
      try {
        const data = JSON.parse(res.data);
        console.log(data);
        if (data.success) {
          callback(data);
        } else {
          callback(false);
          Taro.showToast({
            title: '操作失败',
            icon: 'none',
          });
        }
      } catch (e) {
        callback(false);
      }
    },
    fail: res => {
      Taro.showToast({
        title: res.errMsg.split(' ')[1],
        icon: 'none',
      });
      callback(false);
    },
    complete() {
      // Taro.hideLoading();
    },
  });
};

export default uploadImage;
